<?php

namespace app\admin\controller;

use app\admin\controller\common\Base;

class Admin extends Base
{
  public function index()
  {
    return $this->fetch();
  }
 

  public function list(){
    $data = db('admin')->field('id,admin,role,superadmin,state,sort')->where(['is_del'=>0])->order('sort desc')->select();
    foreach($data as $k=>$v){
      $v['roname'] = db('role')->where(['id'=>$v['role']])->value('name');
      if($v['role'] == 0&&$v['superadmin'] ==1)$v['roname']='超级管理员';
      $data[$k] = $v;
    }
    return ['code'=>0,'data'=>$data];
  }

  public function init(){
    $data = db('role')->field('id,name')->where(['is_del'=>0])->order('sort desc')->select();
    return ['code'=>1,'data'=>$data];
  }

  public function add(){
    return $this->fetch();
  }
  
  public function addvalue(){
    $val = input('post.');
    $data['admin'] = $val['admin'];
    if(db('admin')->where(['admin'=>$val['admin']])->count() !=0)return ['code'=>0,'msg'=>'该用户名已被占用'];
    if($val['pwd1'] !=$val['pwd2'])return ['code'=>0,'msg'=>'两次密码不一致'];
    $data['role'] = $val['role'];
    $data['sort'] = $val['sort'];
    $data['inTime'] = $data['upTime'] = time();
    $data['key'] = sha1($data['inTime']);
    $data['pwd'] = sha1($val['pwd1'].$data['key']);
    $i = db('admin')->insert($data);
    return ['code'=>$i];
  }

  public function find(){
    $id = input('post.id');
    $res = db('admin')->field('admin,role,sort')->where(['id' => $id])->find();
    if ($res) {
        return ['code' => 1, 'data' => $res];
    } else {
        return ['code' => 0];
    }
  }

  public function editval(){
    $val = input('post.');
    if(db('admin')->where(['admin'=>$val['admin']])->count() !=0)return ['code'=>0,'msg'=>'该用户名已被占用'];
    $data['id'] = $val['id'];
    if($val['pwd1'] != $val['pwd2'])return ['code'=>0,'msg'=>'两次密码不一致'];
    $data['role'] = empty($val['role'])?0:$val['role'];
    $data['admin'] = $val['admin'];
    $data['sort'] = $val['sort'];
    $data['upTime'] = time();
    $key = db('admin')->where(['id'=>$data['id']])->value('key');
    $data['pwd'] = sha1($val['pwd1'].$key);
    $res = db('admin')->update($data);
    return ['code' => $res];
  }

   //删除
   public function del(){
    $id = input('post.id');
    $res =  db('admin')->where(['id' => $id])->update(['is_del' => 1, 'upTime' => time()]);
    return ['code'=>$res];
}


}
